package com.zyht.common.util;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;

/**
 * 二维码工具
 * 
 * @author InkYi
 *
 */
public class QRCodeUtil {

	private static String UTF_8 = "UTF-8";

	/**
	 * 生成二维码
	 * @author:InkYi
	 * @time:2016年8月7日 - 下午2:53:40
	 * @description:
	 * @param fileName 文件名
	 * @param suffix 后缀(不包含".")
	 * @param filePath 文件路径
	 * @param content 二维码内容
	 */
	public static void generateQRCode(String fileName, String suffix, String filePath, String content) {
		try {
			MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
			Map<EncodeHintType,Object> hints = new HashMap<>();
			hints.put(EncodeHintType.CHARACTER_SET, UTF_8); //BarcodeFormat.QR_CODE,
			hints.put(EncodeHintType.MARGIN, 0); //白边
			BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, 200, 200, hints);
			//bitMatrix = deleteWhite(bitMatrix);
			File arPaht = new File(filePath);
			if(!arPaht.exists() && !arPaht.isDirectory()){
				arPaht.mkdirs();
			}
			File qrFile = new File(filePath, fileName + "." + suffix);
			
			MatrixToImageWriter.writeToPath(bitMatrix, suffix, qrFile.toPath());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 去除白边
	 * @author:InkYi
	 * @time:2016年8月7日 - 下午3:39:42
	 * @description:会影响图片大小
	 * @param matrix
	 * @return
	 */
	public static BitMatrix deleteWhite(BitMatrix matrix){  
	    int[] rec = matrix.getEnclosingRectangle();  
	    int resWidth = rec[2] + 1;  
	    int resHeight = rec[3] + 1;  
	  
	    BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);  
	    resMatrix.clear();  
	    for (int i = 0; i < resWidth; i++) {  
	        for (int j = 0; j < resHeight; j++) {  
	            if (matrix.get(i + rec[0], j + rec[1]))  
	                resMatrix.set(i, j);  
	        }  
	    }  
	    return resMatrix;  
	}  
	
	public static void main(String[] args) {
		String paht = "E:\\workspace\\.metadata\\.plugins\\org.eclipse.wst.server.core\\tmp0\\wtpwebapps\\wechart_ncb\\upload\\QRCode\\";
		generateQRCode("10086", "jpg", paht, "www.baidu.com");
		
		
	}
}
